'use strict';

const Controller = require('egg').Controller;

class PlanController extends Controller {
    get user() {
        return this.ctx.session.user;
      }
    async allPlans() {
    
        const { ctx } = this;

        console.log(this.user)
        const result = await this.app.mysql.select('plan', {
            plan_user: this.user
        });
        ctx.body = result
    }

    async addPlans() {
        const { ctx } = this;
        let Msg = ctx.request.body;
        console.log(this.user)
        // 接口数据规则
        const rule = {
            plan_title: { type: 'string', required: true },
            plan_budget: { type: 'int', required: true },
            plan_time: { type: 'string', required: false },
            plan_attraction: { type: 'string', required: true },
            plan_place: { type: 'string', required: false }
        };

        try {
            await ctx.validate(rule, Msg);//校验数据
            Msg.plan_user = this.user
            const result = await this.app.mysql.insert('plan', Msg);
            let res = {}
            if (result.affectedRows !== 1) {
                this.ctx.status = 400;
                res.msg = '新建计划失败';
                ctx.body = res;
            }else {
                res.msg = '新建计划成功';
                ctx.body = res;
            }
     
        }
        catch (e) {
            console.log(e);
            ctx.status = 400;
            ctx.body = '请求参数格式不合法'
        }
        
    }
    async deletePlans() {
        const { ctx } = this;
        let id = ctx.request.body.plan_id
        let result1 = await this.app.mysql.delete('plan', {
            plan_id: parseInt(id)
        });
        let res = {}
        if (result1.affectedRows != 1) {
            ctx.status = 400;
            res.msg = '删除计划失败'
            ctx.body = res
        }
        else {
            ctx.status = 200;
            res.msg = '删除计划成功'
            ctx.body = res
        }
    }
    async modifyPlans() {
        const { ctx } = this;
        let id = ctx.request.body.plan_id
        let updateInfo = ctx.request.body.updateInfo
        let result = await this.app.mysql.update('plan', updateInfo, {
            where: {
              plan_id: id
            }
        })
        let res = {}
        if (result.affectedRows != 1) {
            ctx.status = 400;
            res.msg = '更新计划失败'
            ctx.body = res
        }
        else {
            ctx.status = 200;
            res.msg = '更新计划成功'
            ctx.body = res
        }
    }
}
module.exports = PlanController;
